from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

def send():
    from_addr = input('from: ')
    password = input('password: ')
    to_addr = input('to: ')
    smtp_server = input('SMTP server: ')
    msg = MIMEText('hello,send by python...', 'plain', 'utf-8')
    msg['From'] = _format_addr('from_pyLJY<%s>' % from_addr)
    msg['To'] = _format_addr('to_pyJinYang<%s>' % to_addr)
    msg['Subject'] = Header('来自py的问候...', 'utf-8').encode()
    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()
    # 你看到的收件人的名字很可能不是我们传入的，因为很多邮件服务商在显示邮件时，
    # 会把收件人名字自动替换为用户注册的名字，但是其他收件人名字的显示不受影响。

# 使用server = SMTP_SSL(smtp_server)，无需指定端口号
def send2():
    from email import encoders
    from email.header import Header
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.utils import parseaddr, formataddr
    import smtplib
    from smtplib import SMTP_SSL

    def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    from_addr = input('From: ')
    password = input('Password: ')
    to_addr = input('To: ')
    smtp_server = input('SMTP server: ')

    if smtp_server == 'smtp.qq.com':  # 用qq发送则使用授权码
        password = 'omsdqpgzdqfpbjca'  # 需要根据自己QQ的授权码替换

    msg = MIMEMultipart()
    msg['From'] = _format_addr('Python爱好者<%s>' % from_addr)
    msg['To'] = _format_addr('管理员<%s>' % to_addr)
    msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

    msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
    # msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
    #     '<p><img src="cid:0"></p>' +
    #     '</body></html>', 'html', 'utf-8'))
    # with open('C:\Users\asus\Pictures\test.jpg','rb') as f:
    with open('/python_work/test.jpg', 'rb') as f:
        mime = MIMEBase('image', 'jpg', filename='test.jpg')
        mime.add_header('Content-Disposition', 'attachment', filename='test.jpg')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        mime.set_payload(f.read())
        encoders.encode_base64(mime)
        msg.attach(mime)

    # server = smtplib.SMTP(smtp_server,994)
    server = SMTP_SSL(smtp_server)
    # server.starttls()
    server.set_debuglevel(1)
    server.ehlo(smtp_server)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()